package com.dylan.shot.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * Created by Dylan on 2017/10/18.
 */
public class RedisObjectMapper extends ObjectMapper {

    public RedisObjectMapper() {
        super.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        super.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        super.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        super.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    @Override
    public String writeValueAsString(Object value) throws RuntimeException {
        try {
            return super.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("格式化为JSON失败", e);
        }
    }

    @Override
    public <T> T readValue(String content, Class<T> valueType) throws RuntimeException {
        try {
            return super.readValue(content, valueType);
        } catch (IOException e) {
            throw new RuntimeException("解析JSON失败", e);
        }
    }
}
